package no.ntnu.idi.deid.patternmatching.search.dictionary.medicalcodes;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import no.ntnu.idi.deid.config.FilePaths;
import no.ntnu.idi.deid.documentunits.Token;
import no.ntnu.idi.deid.searchresultunits.CategoryTag;
import no.ntnu.idi.deid.searchresultunits.Tag;

/*
 *  ***************************ZIPCODES****************************
 * 
 * Categorytaggen som returneres inneholder bare postnummer og poststed (henholdsvis som code og descrition), mulig dette må utvides!
 * 
 * 
 * Splitter dataen i fila på dollartegn ($), og viktig med en tom linje øverst
 */

public class Zip_Code {
	
	private static Map<String,Zip_Code> ZIPCODES;
	
	private String zip_code; 
	private String place;
//	private String municipality;
//	private String municipalityNumber;
//	private char category;
	
	private Zip_Code(String zip, String pl, String mun, String munNr, char cat){
		zip_code = zip;
		place = pl;
//		municipality = mun;
//		municipalityNumber = munNr;
//		category = cat;
	}
	
	
	
	public static CategoryTag searchInZipcodes(Token searchZip) {
		instantiate();
		Zip_Code zc = ZIPCODES.get(searchZip.getStripped());
		if(zc != null){
			CategoryTag tag = new CategoryTag(Tag.ZIPCODE);
			tag.setValues(zc.zip_code, zc.place);
			return tag;
		}
		return null;
	}
	
	private static void instantiate() {
		if(ZIPCODES==null){
			try {
				readAndMakeZipcodeMap();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private static void readAndMakeZipcodeMap() throws FileNotFoundException {
		ZIPCODES = new HashMap<String,Zip_Code>();
		Scanner sc = new Scanner(new File(FilePaths.getZipCodesPath()));
		while(sc.hasNext()){
			String[] line = sc.nextLine().trim().split("\\$");
			if (line.length==5) {handleLine(line);}
		}
		sc.close();
	}
	
	private static void handleLine(String[] line){
		String zip = line[0].trim();
		String place = line[1].trim();
		String munNr = line[2].trim();
		String mun = line[3].trim();
		char cat = line[4].trim().charAt(0);
		ZIPCODES.put(zip, new Zip_Code(zip, place, mun, munNr,cat));
	}

}
